package jwt

import (
	"github.com/golang-jwt/jwt/v5"
	"web-server/pkg/log"
)

var secret = []byte("FD0DFF6F84EA72B82CE48D8753D946EB")

func GenerateToken(uid int) string {
	logger := log.Default()
	claims := jwt.MapClaims{
		"Uid": uid,
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(secret)
	if err != nil {
		logger.Z.Error("signing failed")
		panic(err)
	}
	return tokenString
}

func ValidateTokenAndGetUid(token string) int {
	if token == "" {
		return 0
	}
	res, _ := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
		return secret, nil
	})
	if claims, ok := res.Claims.(jwt.MapClaims); ok && res.Valid {
		return int(claims["Uid"].(float64))
	}
	return 0
}
